﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Xml;
using System.Xml.Serialization;
using System.Collections.ObjectModel;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Security.Permissions;
using System.Security;

namespace xmltest1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'wales_Media_ArchiveDataSet1.Series_view' table. You can move, or remove it, as needed.
            this.series_viewTableAdapter.Fill(this.wales_Media_ArchiveDataSet1.Series_view);
            // TODO: This line of code loads data into the 'wales_Media_ArchiveDataSet.Series_Season' table. You can move, or remove it, as needed.
            this.series_SeasonTableAdapter.Fill(this.wales_Media_ArchiveDataSet.Series_Season);
            // TODO: This line of code loads data into the 'wales_Media_ArchiveDataSet.Series' table. You can move, or remove it, as needed.
            this.seriesTableAdapter.Fill(this.wales_Media_ArchiveDataSet.Series);
           // DirSearch(@"Z:\Downloads\03.01.2012 Rhian Lewis");
            Debug.WriteLine("plooper 1");
           // RunScript(@"C:\Users\administrator\Scripts\tweek-xml.ps1");
            fillTree();
         }

        void DirSearch(string sDir)
        {
            XmlDocument xdoc = new XmlDocument();
            
            
            
            //XmlNode n = xdoc.SelectSingleNode("/[@xml='/abc/def']");
            //XmlNode p = n.ParentNode;
            //p.RemoveChild(n);
            //System.Xml.XmlNode newNode = xdoc.CreateNode("element", "a", "");
            //newNode.InnerXml = "Hello";
            //p.AppendChild(newNode);
            
            //char[] buff = new char[10000];
            //string[] files = Directory.GetFiles("C:\\", "*.dll")
            Debug.WriteLine("plooper2");
           // try
           // {
                foreach (string d in Directory.GetDirectories(sDir))
                {
                    foreach (string f in Directory.GetFiles(d,"*.xml"))
                    {
                        //lstFilesFound.Items.Add(f);
                        //XmlTextReader reader = new XmlTextReader(f);
                        Debug.WriteLine(f);
                        StreamReader sr = new StreamReader(f);
                        string bx = sr.ReadToEnd();
                        bx = bx.Replace("UTF-8", "UTF-16");
                        bx = bx.Replace("xmlns=", "xmlns:dc=");
                        Debug.WriteLine(bx);
                        xdoc.LoadXml(bx);
                        foreach (XmlNode node in xdoc)
                            if (node.NodeType == XmlNodeType.XmlDeclaration)
                            {
                                xdoc.RemoveChild(node);
                            }
                        //foreach (XmlNode node1 in node.ChildNodes)
                        //    foreach (XmlNode node2 in node1.ChildNodes)
                        //        if (node2.Name == "price")
                        //        {
                        //            Decimal price = Decimal.Parse(node2.InnerText);
                        //            // Increase all the book prices by 20%
                        //            String newprice = ((Decimal)price * (new Decimal(1.20))).ToString("#.00");
                        //            Console.WriteLine("Old Price = " + node2.InnerText + "\tNew price = " + newprice);
                        //            node2.InnerText = newprice;
                        //        }
                        Debug.WriteLine(f);
                        
                        store_xml(f,xdoc);
                    }
                    DirSearch(d);
                }
            //}
            //catch (System.Exception excpt)
            //{
            //   Debug.WriteLine(excpt.Message);
            //}
        }

        void store_xml(string path, XmlDocument xml)
        {    
            string ConnectionString = @"Server=keithjones2c91\sqlexpress;Initial Catalog=xmltest1;User ID=sa;Password=admin;"; 
            SqlConnection conn = new SqlConnection(ConnectionString);
            
            SqlCommand comm = new SqlCommand("INSERT INTO XML2 (PATH, XML) VALUES (@path, @xmlstr)",conn);
            
            SqlParameter p1 = new SqlParameter("@path", SqlDbType.VarChar);
            SqlParameter p2 = new SqlParameter("@xmlstr", SqlDbType.Xml);
            
            p1.Value = path;
            p2.Value = xml.OuterXml;
            comm.Parameters.Add(p1);
            comm.Parameters.Add(p2);
            
            try
            {
                conn.Open();
                comm.ExecuteNonQuery();
                conn.Close();
            }
            catch (System.Exception excpt)
            {
                Debug.WriteLine(excpt.Message);
            }
        
        }


        private string RunScript(string scriptText)
        {
            // create Powershell runspace

            Runspace runspace = RunspaceFactory.CreateRunspace();

            // open it

            runspace.Open();

            // create a pipeline and feed it the script text

            Pipeline pipeline = runspace.CreatePipeline();
            pipeline.Commands.AddScript(scriptText);

            // add an extra command to transform the script
            // output objects into nicely formatted strings

            // remove this line to get the actual objects
            // that the script returns. For example, the script

            // "Get-Process" returns a collection
            // of System.Diagnostics.Process instances.

            pipeline.Commands.Add("Out-String");

            // execute the script
            Collection<PSObject> results = pipeline.Invoke();

            // close the runspace

            runspace.Close();

            // convert the script result into a single string

            StringBuilder stringBuilder = new StringBuilder();
            foreach (PSObject obj in results)
            {
                stringBuilder.AppendLine(obj.ToString());
            }

            return stringBuilder.ToString();
        
        }

        private void seriesBindingNavigatorSaveItem_Click(object sender, EventArgs e)
        {
            this.Validate();
            this.seriesBindingSource.EndEdit();
            this.tableAdapterManager.UpdateAll(this.wales_Media_ArchiveDataSet);

        }
        private void ListDirectory(TreeView treeView, string path)
        {
            treeView.Nodes.Clear();
            var rootDirectoryInfo = new DirectoryInfo(path);
            treeView.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
        }

        private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
        {
            //FileIOPermission f = new FileIOPermission(PermissionState.None);
            //f.AllLocalFiles = FileIOPermissionAccess.Read;
            //try
            //{
            //    f.Demand();
            //}
            //catch (SecurityException s)
            //{
            //    Console.WriteLine(s.Message);
            //}


            var directoryNode = new TreeNode(directoryInfo.Name);
            foreach (var directory in directoryInfo.GetDirectories())
                directoryNode.Nodes.Add(CreateDirectoryNode(directory));
            foreach (var file in directoryInfo.GetFiles())
                directoryNode.Nodes.Add(new TreeNode(file.Name));
            return directoryNode;
        }

        private void tabindexchanged(object sender, EventArgs e)
        {
            ListDirectory(treeView1, @"Z:\Downloads\");
        }

        private void button1_Click(object sender, EventArgs e)
        {
            ListDirectory(treeView1, @"Z:\Downloads\");
        }

        private void treeView1_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            textBox1.Text = treeView1.SelectedNode.FullPath.ToString();
        }
        private void fillTree()
        {
            string[] drives = Environment.GetLogicalDrives();
            foreach (string dr in drives)
            {
                TreeNode node = new TreeNode(dr);
                node.Tag = dr;
                node.ImageIndex = 0; // drive icon
                node.Tag = dr;
                treeView1.Nodes.Add(node);
                node.Nodes.Add(new TreeNode("?"));
            }
            //treeView1.BeforeExpand += new TreeViewCancelEventHandler(treeView1_BeforeExpand);
        }

        void treeView1_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            if ((e.Node.Nodes.Count == 1) && (e.Node.Nodes[0].Text == "?"))
            {
                RecursiveDirWalk(e.Node);
            }
        }

        private TreeNode RecursiveDirWalk(TreeNode node)
        {
            string path = (string)node.Tag;
            node.Nodes.Clear();
            string[] dirs = System.IO.Directory.GetDirectories(path);
            for (int t = 0; t < dirs.Length; t++)
            {
                TreeNode n = new TreeNode(dirs[t].Substring(dirs[t].LastIndexOf('\\') + 1));
                n.ImageIndex = 1; // dir icon
                n.Tag = dirs[t];
                node.Nodes.Add(n);
                n.Nodes.Add(new TreeNode("?"));
            }

            // Optional if you want files as well:
            string[] files = System.IO.Directory.GetFiles(path);
            for (int t = 0; t < files.Length; t++)
            {
                TreeNode tn = new TreeNode(System.IO.Path.GetFileName(files[t]));
                tn.Tag = files[t];
                tn.ImageIndex = 2; // file icon
                node.Nodes.Add(tn);
            } // end of optional file part

            return node;
        }

    }
}
